<template>
  <div class="c-w100 c-h">
    <div id="allmap" class="c-w100 c-h"></div>
  </div>
</template>

<script>
// import { loadBMap } from "@/utils/loadBMap.js"
import { utilJs } from "@/utils/common.js";
export default {
  name: "AddressLocation",
  data() {
    return {
    };
  },
  activated() {
    setDocumentTitle("地址");// eslint-disable-line
    this.$nextTick(function () {
      // loadBMap().then(BMap => {
      //   const map = new BMap.Map("allmap");
      //   // 创建地址解析器实例
      //   const myGeo = new BMap.Geocoder();
      //   // 将地址解析结果显道示在地图上版,并调整地图视野
      //   myGeo.getPoint(this.$route.query.address, function (point) {
      //     if (point) {
      //       map.centerAndZoom(point, 16);
      //       map.addOverlay(new BMap.Marker(point));
      //     } else {
      //       alert("您选权择地址没有解析到结果!");
      //     }
      //   }, this.$route.query.cityName || "北京市");
      // })
      if (window.AMap) {
        this.getAMap();
      } else {
        utilJs.syncLoadJs('https://webapi.amap.com/maps?v=1.4.15&callback=initAMap&key=da83ae2a89855d1b7cb0d07307160fc2');
        window.initAMap = () => {
          this.getAMap();
        }
      }
    })
  },
  methods: {
    getAMap() {
      let geocoderData = null
      let allmap = null
      // 先初始化一遍地图，防止页面空白
      allmap = new AMap.Map('allmap', { // eslint-disable-line
        resizeEnable: true,
        zoom: 13
      })
      const exitDom = new Promise((resolve, reject) => {
        try {
          AMap.service('AMap.Geocoder', function() { // eslint-disable-line
            geocoderData = new AMap.Geocoder({}) // eslint-disable-line
            resolve()
          })
        } catch (error) {
          reject(error)
        }
      })
      Promise.race([exitDom]).then(() => {
        geocoderData.getLocation(this.$route.query.address, function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // 重新设置位置为地图中心
            allmap = new AMap.Map('allmap', { // eslint-disable-line
              resizeEnable: true,
              center: [result.geocodes[0].location.lng, result.geocodes[0].location.lat],
              zoom: 20
            })
            // 设置位置标注
            const marker = new AMap.Marker({ // eslint-disable-line
              position: allmap.getCenter(),
              bubble: true
            })
            marker.setMap(allmap)
          } else {
            console.log('高德地图获取定位失败')
          }
        })
      }).catch(() => {
        console.log('高德地图获取地图实例失败')
      })
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
